import jsonBigint from 'json-bigint'
import axios from 'axios'
import qs from 'qs'

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_URL,
  timeout: 10000,
  transformResponse: (data) => {
    const json = jsonBigint({ storeAsString: true })
    return json.parse(data)
  }
})

instance.interceptors.request.use(
  (config) => {
    config.headers['userId'] = getUserId()
    config.paramsSerializer = (params) => {
      return qs.stringify(params, { indices: false })
    }
    return config
  },
  (error) => {
    return error
  }
)

instance.interceptors.response.use(
  async (response) => {
    const { data, config } = response
    const { code, message } = data

    if (code === _ApiCode.Expire) {
      IMessage(message, 'error')
      useUserStore().Logout()
      return Promise.reject(message)
    } else if (code !== _ApiCode.Success) {
      IMessage(message, 'error')
      return Promise.reject(message)
    } else if (config.method?.toLowerCase() !== 'get') {
      IMessage(message)
    }
    return data
  },
  (error) => {
    console.error('=====error=====')
    console.error(error)
    return Promise.reject(error)
  }
)

export default instance
